<!-- 广告管理 -->
<template>
   <div>
      <div>
         <el-select placeholder="请选择广告状态" style="width: 200px;margin-right: 10px;" v-model="list.status">
            <el-option label="冻结" value="0" />
            <el-option label="激活" value="1" />
         </el-select>
         <el-select placeholder="请选择广告类型" style="width: 200px;margin-right: 10px;" v-model="list.type">
            <el-option :value="item.value" v-for="item in adTypeMap" :label="item.name" />
         </el-select>
         <el-button type="primary" :icon="Search" @click="init">查找</el-button>
         <el-button type="primary" :icon="Plus" @click="addmessage">添加</el-button>
      </div>
      <!-- 创建弹窗 -->
      <el-dialog v-model="dialogFormVisible" :title="isbool ? '创建' : '修改'" width='40%' destroy-on-close>
         <el-form :model="form" ref="ruleFormRef" :rules="rules">
            <!-- 广告标题 -->
            <el-form-item label="广告标题" :label-width="formLabelWidth" prop="title">
               <el-input v-model="form.title" autocomplete="off" />
            </el-form-item>
            <!-- 广告类型 -->
            <el-form-item label="广告类型" prop="type" :label-width="formLabelWidth">
               <el-select placeholder="请选择" style="width: 240px" v-model="form.type">
                  <el-option :label="v.name" :value="v.value" v-for="v in adTypeMap" @click="handleclick(v)" />
               </el-select>
            </el-form-item>
            <!-- 广告图片 -->
            <el-form-item label="广告图片" prop="imgUrl" :label-width="formLabelWidth"
               v-if="form.type && form.type != 6 && form.type != 9" id="uploadImg" style="{background:form.color}">
               <el-upload class="avatar-uploader" action="http://192.168.1.188:8989/upload/admin"
                  :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                  :headers="headers">
                  <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon">
                     <Plus />
                  </el-icon>
               </el-upload>
            </el-form-item>
            <el-form-item label="广告状态" prop="status" :label-width="formLabelWidth">
               <el-switch v-model="form.status" class="ml-2" :active-value='1' :inactive-value='0' />
            </el-form-item>
            <el-form-item label="关联类型" prop="unionType" :label-width="formLabelWidth">
               <el-select :placeholder="form.type == '' ? '请先选择广告类型' : '点击时跳转目标'" style="width: 240px"
                  v-model="form.unionType" :disabled="form.type == ''">
                  <el-option :label="s.name" :value="s.value" v-for="(s, index) in adUinonTypeMap"
                     :disabled="s.value == arr[index] ? false : true" />
               </el-select>
            </el-form-item>
            <el-form-item label="类目" :label-width="formLabelWidth" v-if="form.unionType == 2" prop="unionValue">
               <el-cascader :options="categorys"
                  :props="{ label: 'title', children: 'childrenList', value: 'id', emitPath: false }" clearable
                  v-model="form.unionValue" />
               <el-form-item label="" :label-width="formLabelWidth">
               </el-form-item>
            </el-form-item>
            <el-form-item label="商品" :label-width="formLabelWidth" v-if="form.unionType == 1" prop="unionValue">
               <el-cascader :options="options"
                  :props="{ label: 'label', children: 'children', value: 'id', emitPath: false }" clearable
                  v-model="form.unionValue" />
               <el-form-item label="" :label-width="formLabelWidth">
               </el-form-item>
            </el-form-item>
            <el-form-item label="功能页面" :label-width="formLabelWidth" v-if="form.unionType == 4" prop="unionValue">
               <el-select placeholder="请选择" style="width: 240px" v-model="form.unionValue">
                  <el-option :label="s.name" :value="s.value" v-for="s in functionPages" />
               </el-select>
            </el-form-item>
            <el-form-item label="关键字" :label-width="formLabelWidth" v-if="form.unionType == 3" prop="unionValue">
               <el-input v-model="form.unionValue" autocomplete="off" />
            </el-form-item>
         </el-form>
         <template #footer>
            <span class="dialog-footer">
               <el-button @click="dialogFormVisible = false">取消</el-button>
               <el-button type="primary" @click="handleToggleConfirm(ruleFormRef)">确定</el-button>
            </span>
         </template>
      </el-dialog>
      <!-- 渲染列表 -->
      <el-table :data="tableData" border style="width: 100%;margin-top: 20px;">
         <el-table-column prop="id" label="广告ID" align="center" />
         <el-table-column prop="title" label="广告标题" align="center" width="100" />
         <el-table-column prop="imgUrl" label="广告图片" align="center">
            <template #default="scope">
               <el-popover effect="light" trigger="hover" placement="right" width="300px">
                  <template #default><el-image :src="scope.row.imgUrl" /></template>
                  <template #reference> <el-image :src="scope.row.imgUrl" style="width: 50px;height: 50px;" />
                  </template>
               </el-popover>
            </template>
         </el-table-column>
         <el-table-column prop="type" label="广告类型" align="center">
            <template #default="scope"><el-tag>{{ typelist(scope.row.type) }}</el-tag></template>
         </el-table-column>
         <el-table-column prop="status" label="广告状态" align="center">
            <template #default="scope"><el-tag type="success"> {{ statuslist(scope.row.status) }}</el-tag></template>
         </el-table-column>
         <el-table-column prop="unionType" label="关联类型" align="center">
            <template #default="scope"><el-tag type="warning">{{ unionTypeslist(scope.row.unionType)
}}</el-tag></template>
         </el-table-column>
         <el-table-column prop="unionValue" label="关联[ID]" align="center" />
         <el-table-column prop="gmtCreate" label="创建时间" align="center">
            <template #default="scope">{{ friendTime(scope.row.gmtCreate) }}
            </template>
         </el-table-column>
         <el-table-column prop="" label="操作" align="center" width="150">
            <template #default="scope">
               <div>
                  <el-button size="small" type="primary" @click="handleSwitch(scope.$index, scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="handledelete(scope.$index, scope.row)">删除</el-button>
               </div>
            </template>
         </el-table-column>
      </el-table>
      <Paging v-bind="pagination" @emitfather="CurrentList"></Paging>
   </div>
</template>
<script setup lang="ts">
import { ElMessage, ElMessageBox, type FormInstance, type UploadProps } from 'element-plus';
import { Plus, Search } from '@element-plus/icons-vue'//图标
import { get, post } from '@/utlis/http'
import { friendTime } from '@/utlis/PackagingTime'
import { Classadvert, classPagination } from '#/index'
import Paging from '@/components/paging/Pagings.vue'
import { ref, onMounted, reactive } from 'vue'
import { canvasImgColor } from '@/utlis/canvasImgColor'
import Cookies from 'js-cookie'
const ruleFormRef = ref<FormInstance>()
const pagination = reactive(new classPagination())//分页处理
let tableData = ref([])
let rules = reactive({
   title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
   type: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
   imgUrl: [{ required: true, message: '图片不能为空', trigger: 'blur' }],
   status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
   unionType: [{ required: true, message: '关联不能为空', trigger: 'blur' }],
   unionValue: [{ required: true, message: '关联内容不能为空', trigger: 'blur' }],
})
let list = ref({
   _gp: 'admin.advert',
   _mt: 'list',
   type: '',
   status: '',
   pageNo: 1,
   limit: 10
})
//广告关联类型
const adUinonTypeMap = [
   { value: 1, name: '商品' },
   { value: 2, name: '类目' },
   { value: 3, name: '关键字' },
   { value: 4, name: '功能页面' },
]

//广告类型
const adTypeMap = [
   { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: '轮播' },
   { value: 2, unionTypes: [0, 2], picRequire: true, name: '分类精选' },
   { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: '横幅' },
   { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: '首页轮播下5按钮' },
   { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: '公告' },
   { value: 9, unionTypes: [1], picRequire: false, name: '商品推荐' },
]
//广告状态
const adStatusMap = [
   { value: 0, name: '冻结' },
   { value: 1, name: '激活' },
]


const functionPages = [
   { value: '/pages/product/groupshop', name: '团购列表' },
   { value: '/pages/coupon/list', name: '优惠券列表' },
]
function init() {
   get(list.value).then(res => {
      console.log(res);
      let { errno, data } = res
      if (200 === errno) {
         tableData.value = data.items
         pagination.total = data.total
      }
   })
}
onMounted(() => {
   init()
   advert()
   category()
})
let options = ref()
function advert() {
   let data = {
      _gp: 'admin.product',
      _mt: 'getSpuBigTree'
   }
   get(data).then(res => {
      options.value = res.data
   })
}
let categorys = ref()
function category() {
   let data = {
      _gp: 'admin.category',
      _mt: 'categoryTree'
   }
   get(data).then(res => {
      categorys.value = res.data
   })
}

// 处理广告类型
function typelist(row: number) {
   for (const s of adTypeMap) {
      if (s.value == row) {
         return s.name
      }
   }
}
// 处理广告状态
function statuslist(row: number) {
   for (const s of adStatusMap) {
      if (s.value == row) {
         return s.name
      }
   }
}
// 处理关联类型
function unionTypeslist(num: number) {
   for (const i of adUinonTypeMap) {
      if (i.value == num) {
         return i.name
      }
   }
}
let dialogFormVisible = ref(false)
let formLabelWidth = '80px'
let form = ref(new Classadvert())
// 切换禁用
let arr = ref([])
function handleclick(s: any) {
   // arr.value = s.unionTypes
   for (const i in adUinonTypeMap) {
      if (adUinonTypeMap[i].value==s.unionTypes[i]) {
         arr.value = s.unionTypes
      }else{
         form.value.unionType=""
      }
   }
   if (s.picRequire==false) {
      form.value.imgUrl=''
   }
}
let isbool = ref(false)
// 添加弹出框
function addmessage() {
   isbool.value = true
   dialogFormVisible.value = true
   form.value = new Classadvert()
}
// 表单验证与添加编辑
function handleToggleConfirm(formEl: FormInstance | undefined) {
   if (!formEl) return
   formEl.validate((valid) => {
      if (valid) {
         if (!form.value.imgUrl) {
            form.value.imgUrl = 'https://www.baidu.com/img/flexible/logo/pc/result.png'
         }
         let create = {
            _gp: 'admin.advert',
            _mt: isbool.value ? 'create' : 'edit',
            ...form.value
         }
         post(create).then(res => {
            let { errmsg, errno } = res
            if (200 == errno) {
               dialogFormVisible.value = false
               ElMessage.success(errmsg)
               init()
            } else {
               ElMessage.error(errmsg)
            }

         })

      } else {
         return false
      }
   })

}
let Currenttype = ref()
// 编辑弹出框
function handleSwitch(index: number, row: Classadvert) {
   if (row.unionType == 1 || row.unionType == 2) {
      row.unionValue = Number(row.unionValue)
   }
   if (row.type == 6 || row.type == 9) {
      form.value.imgUrl = ""
   }
   // 当前广告类型
   Currenttype.value = adTypeMap.find(s => s.value == row.type)
   console.log(Currenttype.value);

   dialogFormVisible.value = true
   Object.assign(form.value, { ...row, adId: row.id })
   isbool.value = false
}

// 删除
function handledelete(index: number, row: Classadvert) {
   let data = {
      _gp: 'admin.advert',
      _mt: 'delete',
      type: row.type,
      adId: row.id
   }
   post(data).then(res => {
      ElMessageBox.confirm(
         '确定删除吗?',
         'Warning',
         {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
         }
      )
         .then(() => {
            ElMessage({
               type: 'success',
               message: '成功',
            })
            init()
         })
         .catch(() => {
            ElMessage({
               type: 'info',
               message: '取消d',
            })
         })

   })
}
// 图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (
   response,
   uploadFile
) => {
   // form.value.imgUrl = URL.createObjectURL(uploadFile.raw!)
   form.value.imgUrl = response.url
   canvasImgColor(form.value.imgUrl, (reba: string) => {
      form.value.color = reba
   })
}
let headers = reactive({
   'AdminToken': Cookies.get('token')
})
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
   if (rawFile.type !== 'image/jpeg') {
      ElMessage.error('Avatar picture must be JPG format!')
      return false
   } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('Avatar picture size can not exceed 2MB!')
      return false
   }
   return true
}
// 分页
function CurrentList(v: classPagination) {
   list.value.pageNo = v.pageNo
   list.value.limit = v.pageSize
   init()
}



</script>
<style scoped>
.img {
   width: 60%;
}

.ml-2 {
   --el-switch-on-color: #13ce66;
   --el-switch-off-color: #ff4949
}

.avatar-uploader .avatar {
   width: 178px;
   height: 178px;
   display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
   border: 1px dashed var(--el-border-color);
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
   transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
   border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
   font-size: 28px;
   color: #8c939d;
   width: 178px;
   height: 178px;
   text-align: center;
}
</style>